import *  as os from 'os';
import *  as fs from 'fs';
import *  as path from 'path';
import * as log4js from 'log4js';

export function installConfigDirPre() {
	// 获取用户目录
	const userHome = os.homedir();
	// 创建日志目录
	const configDir = `${userHome}/.config/Kylin-Code/installconfig`;
	if (!fs.existsSync(configDir)) {
		fs.mkdirSync(configDir, { recursive: true }); // 递归创建目录
	}
	return configDir;
}

//读取使用的配置文件的存放路径
// 1.如果没有selectfile.json，则使用的为/usr/share、...目录下的配置文件
// 2.如果存在selectfile.json，则使用的配置文件地址为selecDir的值
export function localConfigPath() {
	let localConfigDir = path.join(path.dirname(__dirname), "../../../config/");
	if (fs.existsSync(installConfigDirPre() + '/' + 'selectFile.json')) {
		let jsonContent = fs.readFileSync(installConfigDirPre() + '/' + 'selectFile.json', 'utf-8');
		let jsonData = JSON.parse(jsonContent);
		let selectDir = jsonData['selectDir'];
		if (selectDir && fs.existsSync(selectDir))
			return selectDir;
	}
	return localConfigDir;
}
//读取使用的配置文件的存放路径
// 1.如果没有selectfile.json，则使用的为/usr/share、...目录下的配置文件
// 2.如果存在selectfile.json，则使用的配置文件地址为selecDir的值
export function selectFileJson() {
	let selectJSON = null;
	if (fs.existsSync(installConfigDirPre() + '/' + 'selectFile.json')) {
		let jsonContent = fs.readFileSync(installConfigDirPre() + '/' + 'selectFile.json', 'utf-8');
		selectJSON = JSON.parse(jsonContent);
		return selectJSON;
	}
	return selectJSON;
}

export function getDateDir() {
	const currentD = new Date().getTime();
	// const datasttr = currentD.toLocaleDateString();
	// let name = datasttr.replace(/\//g, '')
	return currentD;
}
export function modifyJsonProperty(filePath: string, propertyName: string, newValue: string | string[]) {
	let jsonData;
	if (fs.existsSync(filePath)) {
		const fileContent = fs.readFileSync(filePath, 'utf-8');
		jsonData = JSON.parse(fileContent);
	} else {
		jsonData = {};
	}
	if (propertyName === "selectKey") {
		if (jsonData[propertyName]) {
			let tmp = jsonData[propertyName];
			tmp.push(...newValue);
			let tmparry = [...new Set(tmp)];
			jsonData[propertyName] = tmparry;
			console.log("selectKey setset:" + jsonData[propertyName]);
		} else {
			jsonData[propertyName] = newValue;
		}
	} else {
		jsonData[propertyName] = newValue;
	}

	const modifiedContent = JSON.stringify(jsonData, null, 2);
	fs.writeFileSync(filePath, modifiedContent, 'utf-8');

}
export const compareVersions = (v1: string, v2: string) => {
	// validate input and split into segments
	const n1 = validateAndParse(v1);
	const n2 = validateAndParse(v2);

	// pop off the patch
	const p1 = n1.pop();
	const p2 = n2.pop();

	// validate numbers
	const r = compareSegments(n1, n2);
	if (r !== 0) return r;


	if (p1 && p2) {
		return compareSegments(p1.split('.'), p2.split('.'));
	} else if (p1 || p2) {
		return p1 ? -1 : 1;
	}

	return 0;
};

const semver =
	/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;

const validateAndParse = (version: string) => {
	if (typeof version !== 'string') {
		throw new TypeError('Invalid argument expected string');
	}
	const match = version.match(semver);
	if (!match) {
		throw new Error(
			`Invalid argument not valid semver ('${version}' received)`
		);
	}
	match.shift();
	return match;
};

const tryParse = (v: string) => {
	const n = parseInt(v, 10);
	return isNaN(n) ? v : n;
};

const forceType = (a: string | number, b: string | number) =>
	typeof a !== typeof b ? [String(a), String(b)] : [a, b];

const compareStrings = (a: string, b: string) => {
	const [ap, bp] = forceType(tryParse(a), tryParse(b));
	if (ap > bp) return 1;
	if (ap < bp) return -1;
	return 0;
};

const compareSegments = (
	a: string | string[],
	b: string | string[]
) => {
	for (let i = 0; i < Math.max(a.length, b.length); i++) {
		const r = compareStrings(a[i] || '0', b[i] || '0');
		if (r !== 0) return r;
	}
	return 0;
};
export function logDirectory() {
	const installConfigDir = installConfigDirPre();
	const logDirectory = `${installConfigDir}/log`;
	if (!fs.existsSync(logDirectory))
		fs.mkdirSync(logDirectory, { recursive: true }); // 递归创建目录
	return logDirectory;
};

log4js.configure({
	appenders: {
		file: {
			type: 'file',
			filename: `${logDirectory()}/instguide.log`
		}
	},
	categories: {
		default: { appenders: ['file'], level: 'info' }
	}
});
export const logger = log4js.getLogger();

// 获取用户目录

